<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
      @changeAddress="changeAddress"
    ></VForm>

    <div v-for="(valueList, itemType) in taskItemMap" style="margin-bottom: 10px">
      <div class="formTitle-root">
        <div class="form-title-p">{{itemType}}</div>
      </div>
      <el-table :data="valueList" border>
        <el-table-column prop="itemType" label="巡查项名称">
          <template slot-scope="scope">
            <el-input type="text" :disabled=true v-model="scope.row.itemName"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="itemName" label="巡查结果" width="140px">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.result"
              filterable
              placeholder="巡查结果"
              :disabled="openType=='detail'"
            >
              <el-option
                v-for="item in patrolTaskResultOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="sceneSituation" label="现场情况">
          <template slot-scope="scope">
            <el-input
              type="textarea"
              v-model="scope.row.sceneSituation"
              :rows="4"
              placeholder="现场情况"
              :disabled = "openType=='detail'"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="sceneSituation" label="现场照片">
          <template slot-scope="scope">
              <eleVUpload
                ref="eleVUpload"
                :disabled="openType=='detail'"
                upload-type="image"
                listType="picture-card"
                uploadTextTip=" "
                :fileList="scope.row.scenePic"
                @upLoadSuccess="uploadChangeFIleItem($event,scope.row.id, scope.row.itemType)"
                @removeFileList="removeChangeFIleItem($event,scope.row.id, scope.row.itemType)"
              ></eleVUpload>
          </template>
        </el-table-column>
        <el-table-column prop="sceneSituation" label="是否发现隐患">
          <template slot-scope="scope">
            <div>
              <div style="display: inline-block;"><el-checkbox v-model="scope.row.existHazard" :disabled = "openType=='detail'" /></div>
              <div style="display: inline-block; margin-left: 5px;width: 90%"> <el-input
                type="textarea"
                :rows="4"
                v-model="scope.row.hazardName"
                placeholder="隐患内容"
                :disabled = "openType=='detail'"
              ></el-input></div>
            </div>
            <div style="margin-top: 10px" v-if="formData.form.status == 2 && scope.row.existHazard && openType == 'detail' ">
              隐患状态：{{getHazardState(scope.row)}}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="formTitle-root">
      <div class="form-title-p">其他情况</div>
    </div>
    <VForm
      ref="vformComponents1"
      :form="formDataOther.form"
      :options="formDataOther.options"
      :rules="formDataOther.rules"
      :labelWidth="formDataOther.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <span slot="footer" class="dialog-footer">
     <el-button @click="cancel">{{openType!='detail' ? '取 消':'返 回'}}</el-button>
     <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    patrolPatrolTaskDetail,
    patrolPatrolTaskUpdate
  } from '@/api/risk/patrol'
  import { treeDataChild } from '@/api/risk/treeData'
  import VForm from "@/components/VForm/index";
  import eleVUpload from '@/components/eleUpload/eleUpload'
  import { collectBuildingProjectList } from '@/api/build/project'
  export default {
    components: {
      VForm,eleVUpload
    },
    props: {
      width: {
        type: String,
        default: "80%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id:{},
      openType:{
        type:String,
        default:"add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      bClassifyOptions:{},
      patrolTaskResultOptions:{}
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          let w = this.width.split('%')[0]
          if(w>=60){
            this.rowspan = 2
          }else{
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'bClassifyOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiLargeType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptionsForm':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiSmallType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'formData.form.busiLargeType':{
        handler(newVal, oldVal) {
          this.watchChangeLargeType()
        },
        deep: true,
        immediate: true
      },
      'openType':{
        handler(newVal, oldVal) {
          // 判断是否详情，添加不可编辑标识
          this.formData.options.forEach(t=>{
            if(!t.df){
              t.disabled = newVal=='detail' ? true : false
            }
          })
          this.formDataOther.options.forEach(t=>{
            t.disabled = newVal=='detail' ? true : false
          })
        },
        deep: true,
        immediate: true
      },
      'planTypeOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='planType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'patrolTaskStatusOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='status'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'buildingOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'buildingId') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        rowspan:1,
        dict:{},
        taskItemMap:{},
        formDataOther:{
           form:{
             other:"",
             otherPic:[]
           },
           options:[
             {
               title: "现场照片",
               key: "otherPic",
               type: "file",
               fileType: "image",
               listType: "picture-card",
               uploadTextTip: "",
               columnWidth: 'w100max'
             },
             {
               title: "现场情况",
               key: "other",
               type: "textarea",
               columnWidth: 'w100max',
             },
           ],
           rules:{},
           labelWidth: "140px",
        },
        formData: {
          form: {
            id:"",
            patrolNo:"",
            planName:"",
            busiLargeType:"",
            busiSmallType:"",
            planType:"",
            patrolObjectName:"",
            modelName:"",
            patrolAddress:"",
            lon:"",
            lat:"",
            patrolStartTime:"",
            patrolEndTime:"",
            patrolPerson:"",
            status:"",
            mapData:null,
            buildingId: "",
          },
          options: [
            {
              title: "所属工地",
              key: "buildingId",
              type: "select",
              multiple: false,
              df:true,
              option: {
                data: this.buildingOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "projectName", // 指定label对应data的字段
                  value: "id", //指定value对应data的字段
                }
              },
              disabled:true
            },
            {
              title: "巡查编号",
              key: "patrolNo",
              type: "text",
              df:true,
              disabled:true
            },
            {
              title: "所属计划",
              key: "planName",
              type: "text",
              df:true,
              disabled:true
            },
            {
              title: "业务分类",
              key: "busiLargeType",
              type: "select",
              multiple:false,
              df:true,
              disabled:true,
              event: 'changeLargeType',
              option: {
                data: this.bClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },
            {
              title: "业务细类",
              key: "busiSmallType",
              type: "select",
              df:true,
              disabled:true,
              multiple:false,
              option: {
                data: this.sClassifyOptionsForm,
                props: {
                  key: "code", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "code", // 指定value对应data的字段
                },
              },
            },
            {
              title: "巡查类型",
              key: "planType",
              type: "select",
              df:true,
              disabled:true,
              multiple:false,
              option: {
                data: this.planTypeOptions,
                props: {
                  key: "value", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "巡查对象",
              key: "patrolObjectName",
              type: "text",
              df:true,
              disabled:true,
            },
            {
              title: "巡查表单",
              key: "modelName",
              type: "text",
              df:true,
              disabled:true,
            },
            {
              title: "巡查人",
              key: "patrolPerson",
              type: "text",
              df:true,
              disabled:true,
            },
            {
              title: "巡查状态",
              key: "status",
              type: "select",
              multiple:false,
              option: {
                data: this.patrolTaskStatusOptions,
                props: {
                  key: "value", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title:'巡查地址',
              type:'mapPosition',
              key:'mapData',
            },
            {
              title: "巡查开始时间",
              key: "patrolStartTime",
              type: "datetime",
            },
            {
              title: "巡查结束时间",
              key: "patrolEndTime",
              type: "datetime",
            },
          ],
          rules: {
            patrolStartTime :[
              { required: true, message: '请选择', trigger: ['blur',] },
            ],
            patrolEndTime :[
              { required: true, message: '请选择', trigger: ['blur',] },
            ],
          },
          labelWidth: "140px",
        },
        // 字典
        sClassifyOptionsForm:[],
        planTypeOptions:[],
        patrolTaskStatusOptions:[],
        hazardProcessStateOptions:[],
        buildingOptions: [],
      };
    },
    methods: {
      getHazardState(row){
       // 1:待派单，2:整改中，9 已归档
         if(row.hazardState!=null){
           let item =  this.hazardProcessStateOptions.find(t=>t.value == row.hazardState)
           if(undefined!=item){
             return item.label
           }
         }
         return '-'
      },
      changeAddress(data){
        this.formData.form.mapData = data
      },
      removeChangeFIleItem(e, id, itemType){
       let item =  this.taskItemMap[itemType].find(t=>t.id == id)
        if(undefined!=item){
          item.scenePic =  e
        }
      },
      uploadChangeFIleItem(e, id, itemType){
        let item =  this.taskItemMap[itemType].find(t=>t.id == id)
        if(undefined!=item){
          item.scenePic =  e.newFileList
        }
      },
      noBlank(val) {
        if (val != "" && val != null && val != undefined) {
          return true;
        }
        return false;
      },
      toLoadMethods(methods) {
        this[methods]()
      },
      watchChangeLargeType(){
        let queryData ={}
        queryData.name='hazardBClassify';
        queryData.code =this.formData.form.busiLargeType
        treeDataChild(queryData).then(res=>{
          if(res.code==200) {
            this.sClassifyOptionsForm = res.data
          }
        })
      },
      initData(){
          this.formData.form.id = "",
          this.formData.form.patrolNo = "",
          this.formData.form.planName = "",
          this.formData.form.busiLargeType = "",
          this.formData.form.busiSmallType = "",
          this.formData.form.planType = "",
          this.formData.form.patrolObjectName = "",
          this.formData.form.modelName = "",
          this.formData.form.patrolAddress = "",
          this.formData.form.lon = "",
          this.formData.form.lat = "",
          this.formData.form.patrolStartTime = "",
          this.formData.form.patrolEndTime = "",
          this.formData.form.patrolPerson = "",
          this.formData.form.status = "",
          this.formData.form.mapData = null,
          this.sClassifyOptionsForm = []
      },
      sure(){
        console.log('sure===',this.formData.form)
        this.$refs.vformComponents.$refs.form.validate().then(res=>{
          if(this.formData.form.patrolAddress.length>36){
             this.$message.warning("巡查地址长度不能大于36位")
             return
          }
          let patrolTaskItemList = []
          let taskItemMapTemp = Object.assign(this.taskItemMap)
          let flag = 1;
          for(let key in taskItemMapTemp){
              let list  = taskItemMapTemp[key]
              list.forEach(t=>{
                if(this.formData.form.status==2){
                    if(!this.noBlank(t.result) && t.result!=0){
                      flag = 2
                      return;
                    }
                    if(this.noBlank(t.existHazard) && !this.noBlank(t.hazardName)){
                      flag = 3
                      return;
                    }
                    if(this.noBlank(t.hazardName) && !this.noBlank(t.existHazard)){
                       t.existHazard = true
                    }
                }
                t.existHazard =  t.existHazard == true ? 1 : 0
                t.scenePic = JSON.stringify(t.scenePic);
                patrolTaskItemList.push(t)
              })
          }
          if(flag!=1){
            if(flag == 2){
              this.$message.warning("请完善巡查结果")
            }
            if(flag == 3){
              this.$message.warning("请完善隐患内容")
              flag = 3
            }
            return;
          }
          let tempMapData = this.formData.form.mapData
          this.formData.form.patrolAddress = tempMapData.address
          this.formData.form.lon =  tempMapData.gpsX
          this.formData.form.lat =  tempMapData.gpsY
          let tempParam = {
            ...this.formData.form,
            ...this.formDataOther.form,
            patrolTaskItemList:patrolTaskItemList
          }
          tempParam.otherPic = JSON.stringify(tempParam.otherPic);
          console.log("tempParam===",tempParam)
          if(this.openType == "add"){
            this.add(tempParam)
          }else{
            this.update(tempParam)
          }
        })
      },
      add(tempParam){
        //   tempParam.id = null
        //   patrolModelAdd(tempParam).then(res=>{
        //   if(res.code==200){
        //     this.$message({
        //       message: this.$t('tips.createSuccess'),
        //       type: 'success'
        //     })
        //     this.closeSuccess()
        //   }else{
        //     this.$message({
        //       message: res.message,
        //       type: 'error'
        //     })
        //   }
        // })
      },
      update(tempParam){
        patrolPatrolTaskUpdate(tempParam).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      cancel(){
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('success')
      },
      close(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('close')
      },
      loadFormat(data){
        let tempMap = {}
        for(let type in data.patrolTaskItemListMap){
          let valueList = data.patrolTaskItemListMap[type]
          valueList.forEach(t=>{
               let tempItemPic = []
               if(t.scenePic){
                 tempItemPic = JSON.parse( t.scenePic).map(item=>{
                   return{
                     name:item.name,
                     url: process.env.VUE_APP_BASE_API + 'file/api/download/'+item.fileId,
                     uid: item.uuid,
                     fileId: item.fileId,
                   }
                 })
               }
               t.scenePic = tempItemPic
               t.existHazard =  t.existHazard == 1 ? true : false
          })
          tempMap[type] = valueList
        }
        console.log("===============",tempMap)
        this.taskItemMap = tempMap
        this.formDataOther.form.other = data.other
        this.formDataOther.form.otherPic = []
        if(data.otherPic){
          this.formDataOther.form.otherPic = JSON.parse( data.otherPic ).map(item=>{
            return{
              name:item.name,
              url: process.env.VUE_APP_BASE_API + 'file/api/download/'+item.fileId,
              uid: item.uuid,
              fileId: item.fileId,
            }
          })
        }
        let mapData = {}
        mapData.address = data.patrolAddress
        if(data.lon) {
          mapData.gpsX = parseFloat(data.lon)
        }
        if(data.lat) {
          mapData.gpsY = parseFloat(data.lat)
        }
        this.formData.form.mapData = mapData
        console.log("this.formData.form====,mapData",this.formData.form, mapData)
      },

      getBuildingList() {
        collectBuildingProjectList().then(res => {
          if (res.code == 200) {
            this.buildingOptions = res.data
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },

      getData(){
          this.planTypeOptions= []
          this.$commonJs.filterDataDict("patrolPlanType",this.planTypeOptions)
          this.patrolTaskStatusOptions = []
          this.$commonJs.filterDataDict("patrolTaskStatus",this.patrolTaskStatusOptions)
          this.hazardProcessStateOptions = []
          this.$commonJs.filterDataDict("hazardDealState",this.hazardProcessStateOptions)
          this.getBuildingList();
        if(this.openType!="add"){
          patrolPatrolTaskDetail(this.id).then(res=>{
            if(res.code==200){
              this.formData.form = res.data
              this.loadFormat(res.data)
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }
      }
    },
  };
</script>

<style lang="scss" scoped>
  @import "@/styles/element-variables.scss";
  .formTitle-root{
    padding: 10px 0;
    border-bottom: 1px solid #EFEFEF;
    font-size: 16px;
    position: relative;
    margin-bottom: 10px;
    .form-title-p{
      padding-left: 10px;
      border-left: 4px solid $--color-primary;
    }
  }
  /*修改禁用样式*/
  ::v-deep .is-disabled .el-input__inner  {
    background-color:white;
    color: rgb(0, 0, 0);
  }
  ::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner{
    border-color: $--color-primary;
    background: $--color-primary;
  }
  ::v-deep .el-radio__input.is-disabled + span.el-radio__label{
    color: rgb(0, 0, 0);
  }
  ::v-deep .el-textarea.is-disabled .el-textarea__inner{
    background: white;
    color: rgb(0, 0, 0);
  }
</style>
